<template>
  <div class="page-container padding-20">
    <el-form class="el-form-modify" ref="form" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="站点名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入站点名称"></el-input>
      </el-form-item>
      <el-form-item label="站点ID">
        <span>{{formData.cid}}</span>
      </el-form-item>
      <el-form-item label="所属品牌" prop="brandId">
        <el-select v-model="formData.brandId">
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.name"
            :value="brand.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="站点级别" prop="level">
        <el-select v-model="formData.level">
          <el-option 
            v-for="level in levelList"
            :key="level.value"
            :label="level.label"
            :value="level.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="regionCodes">
        <area-select v-model="formData.regionCodes" :emitPath="true" 
          @labelChange="labelChange" style="width: 100%;"></area-select>
      </el-form-item>
      <el-form-item label="">
        <el-input v-model="formData.address" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button size="mini" type="primary" @click="positionArea">定位到所选区</el-button>
        <el-button size="mini" type="primary" @click="addMarker" :disabled="!!this.bmMarker">添加标注</el-button>
        <el-button size="mini" type="primary" @click="deleteMarker" :disabled="!this.bmMarker">删除标注</el-button>
        <baidu-map :option="mapOption" @ready="mapReady" :bmMarker="bmMarker"
          @markerDragend="markerDragend" style="height: 300px;">
        </baidu-map>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
        <el-button @click="cancel(false)" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {cinemaAdd, cinemaEdit, cinemaDetail} from '@/api/cinema'
import AreaSelect from '@/components/AreaSelect'
import BaiduMap from './BaiduMap';
import {rules} from '@/utils/validate';
import {SITE_LEVEL} from '@/utils/const';

export default {
  name: 'CinemaForm',
  components: {
    BaiduMap,
    AreaSelect
  },
  props: ['brandList'],
  data() {
    let formData = {
        brandId: "",
        name: "",
        address: "",
        level: 'ONE',
        latitude: "",
        longitude: "",
        regionCodes: "",
        regionName: ""
      };
    return {
      levelList: Object.keys(SITE_LEVEL).map(item => {
        return {value: item, label: SITE_LEVEL[item]};
      }),
      mapOption: {
        center: formData.regionName || '北京'
      },
      formData,
      rules: {
        brandId: [rules.select_required],
        name: [rules.required, rules.text2_32],
        regionCodes: [rules.select_required],
        address: [rules.required, rules.text2_128]
      },
      saving: false,
    }
  },
  computed: {
    bmMarker() {
      let {longitude, latitude} = this.formData;
      return longitude ? {position: {lng: this.formData.longitude, lat: this.formData.latitude}, dragging:true} : null
    }
  },
  methods: {
    labelChange(label) {
      this.formData.regionName = label
    },
    mapReady({BMap, map}) {
      let {regionName} = this.formData;
      this.map = map;
      if (latitude) {
        this.mapOption = {
          center: regionName
        };
      }
    },
    positionArea() {
      if (this.map) {
        if (this.formData.regionName) {
          this.map.setCenter(this.formData.regionName);
        } else {
          this.$message.warning('请选择地区');
        }
      } else {
        this.$message.warning('地图初始化中，稍后重试');
      }
    },
    markerDragend({point}) {
      this.formData.latitude = point.lat;
      this.formData.longitude =  point.lng;
    },
    addMarker() {
      if(this.map) {
        const {regionName, address} = this.formData;
        var myGeo = new BMap.Geocoder();
        myGeo.getPoint(regionName + ' ' + address, (point) => {
          if (point) {
            this.map.centerAndZoom(point, 14);
            this.formData.longitude = point.lng;
            this.formData.latitude = point.lat;
          } else {
            this.$message.warning('您输入的地址在地图中未找到，请重新输入地址!');
          }
        }, "");
      }
    },
    deleteMarker() {
      this.formData.latitude = ""
      this.formData.longitude =  ""
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          const method = this.formData.id ? cinemaEdit : cinemaAdd
          let saveData = {...this.formData}
          await method(saveData)
          this.saving = false;
          this.$message.success('保存成功!');
          this.cancel(true);
        } catch(err) {
          this.saving = false;
        }
      })
    },
    cancel(refersh = false) {
      if (refersh) {
        this.$emit('refresh');
      }
      this.$router.go(-1)
    },
    async requestDetial(id) {
      try {
        const {data} = await cinemaDetail(id)
        if (data) {
          Object.assign(this.formData, data);
          this.formData.name = data.cinemaName;
          this.formData.regionCodes = data.regionCodes.split(',');
          if (this.map && data.latitude) {
            this.mapOption = {
              center: data.regionName
            };
          }
        }
      } catch (error) {
      }
    }
  },
  created() {
    if (this.$route.name == 'editCinema') {
      let {id} = this.$route.params;
      if (id) {
        this.requestDetial(id)
      } else {
        this.cancel()
      }
    }
  }
}
</script>

<style lang="scss">
  .bm-view{
    height: 240px;
  }
</style>